# $Id: s_main.py 41 2012-09-04 15:00:35Z Administrator $
# -*- coding: utf-8 -*-
import __init__
import time
import pygame
import netstream
import events
import msg_define
import header
import common_const
import s_global
import s_service
import s_sender
import s_spritemgr
import s_playermgr
import s_aoimgr

class main_instance(object):
	def __init__(self):
		self.host_instance = None
		self.msg_dispatcher = None
		self.sprite_mgr = None
		self.player_mgr = None
		self.cur_frame = 0

	def start_game(self):
		self.init_instance()
		self.init_setting()
		self.game_loop()
		
	def init_instance(self):
		 self.host_instance = netstream.nethost()
		 self.host_instance.startup(2000)
		 self.msg_dispatcher = s_service.dispatcher(s_global.service_cls)
		 self.sprite_mgr = s_spritemgr.sprite_mgr()
		 self.player_mgr = s_playermgr.player_mgr()
		 self.aoi_mgr = s_aoimgr.aoi_mgr()
		 s_global.sender = s_sender.sender(self.host_instance)
		 
	def init_setting(self):
		pass

	def client_leave(self, sockid):
		self.host_instance.close(sockid)
		
	def handle_event(self):
		while (1):
			event, client_id, client_tag, recv_msg = self.host_instance.read()
			if event < 0:
				break
			if event == netstream.NET_DATA:      
				msg_type = header.getmsgtype(recv_msg)
				msg = events.msg_class[msg_type]()
				msg.unmarshal(recv_msg)
				service_id,command_id = msg_define.msg_svc_cmd[msg.type]
				msg.append_param('sid',service_id,'i')
				msg.append_param('cid',command_id,'i')
				self.msg_dispatcher.dispatch(msg, client_id)
			elif event == netstream.NET_LEAVE:
				pass
	
	def logic_frame(self):
		self.cur_frame += 1
		self.host_instance.process()
		self.handle_event()
	
	def game_loop(self):  
		server_alive = True
		frames_per_sec = common_const.svr_fps
		clock = pygame.time.Clock()
		while server_alive:
			#print clock.get_fps()
			self.logic_frame()
			clock.tick(frames_per_sec)
                  
if __name__ == "__main__":
	s_global.main_ins = main_instance()
	s_global.main_ins.start_game()


     
